package com.feri.fc.pay.alipay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/15 17:00
 * @Modified:
 */
public class AliPayUtil {
    /**
     * 商户签约时，对应的应用id*/
    private static final String APP_ID="2017091608770636";
    /**
     * 商户签约时，自己生成的私钥(RSA)*/
    private static final String PRIVATE_KEY="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCh1qI8uo1qhrcePsa5JUAoYUX8HfPuBt7kc90aCP1M/v61/uzaU/lyGQeChKV3jdDTn2Lcq6kT5JBl3TLiaYHmO6cId1nQAIUxiT9zhB9crc4wAx8CVabMbcqUefs7Xsp+YhhUgU5X6GOS3emkUeL7RegBnL8vayfEBeUDgBxsk/K/VygBA8sapsEhnoOrB6bhMY4GaJrxb0kg9Ej8x4kpExLcxkT+UgcOiJvh6vpBZo5CJsiPQkFvSsNsWY2uSDudSL/KqpMxz+yPfVvZDt4fOfyi+CfYR43Jlo4tsT7joqH2JT06BH+KdJyc1D3Lqw7w/WdmZtmoLghH0kRZawrLAgMBAAECggEAYYtpm+rhQ7zQ8HTr+DogknYW5Z/0H5qai93d/Uw/yEHFqlJt1iZZKlE1upBS311l6beesdzxeuD/u7X4bokjV27K/YpaYsl9fl74FJslAApuRXgMH68aawsd2CIxsBYxPL3JZl3Np6SVJ7eDlJwakFMRRK+CeIVAoaDf6R01hKctkYnnE0wT+ffQNKWsISoEyiKVT3g5fur7iPOuDlDXsfi6Mm+e75wCXTmRRHmb8lPBAMLV+Kj5DFxg8dwNz81Fs4ZM2Aq0lBaTfy1H1zSlM1m42wcsMYDcgdEH9aq+OgqK+cny6umgs7/Alg7IgV/9b7AhKdvAqLy2ERUJtooj2QKBgQDeIoDW3HuTq7sBaBnu63f7icT2RM3fApfOiGM4UDtxPvc5dS5S//o3E8p+rbp21FfBeyLOJFd9dg/eu+ETA+63QMPw4Kq4AH/EA5AFohaOQ0IKFDjYyxfyD8ajA4USDwdiaW2/vmMeAtGSv+W5zWb9/t49LOTwzEW904+yOGcmhQKBgQC6guDZ0Ob4o9nx5XwZXEe2di4MupARHceGzmolyDvs3Qi/w+8QntrDvfqIJoqoxOG5NVi3jtjkqtJtMaPyxqNWTabWOOTLbrsqlvPUmeCl0j3FVFKAGcV7/b9XkLvh1DtnIe6rhhZCVB4e4bL/katpOTgulhmSMaWIaztGU0F1DwKBgQCTeobdn/6vuSlsMqhdFppPN1W8R0wDjt4o8iYlwibk9e//hswdsPN307zyQ/dzY2FsBIvEHx6zHkpFD6nMDSVVJzuv1gmiJjqtccwR4V5mT0MuG+TuElCwlkbD/ddAeRfm/6Ys0oNN7oMjkiI8LKH/alI0fXT2Zji7YhWaNpZNXQKBgEU6q0duWS1VdGJrcgLf0+aQO0uSPEN+MD+Dgrb/ee7TpJm5mpUqwb0CWWoMFE/MtJRQjtujdDJ8jZrmYBqPTLWOIS1G9PXl5idK3Lq/Wzlxrmf+gpj19+2sJEfWe0a5xkrjt3mHTd/U5VFFKXHfmiZ2jLoOEPPI5c6bLudNo/BVAoGBAMvwRxLO4xb11Ip4rnEHkw3Qn8lrddoC3/m7haHYZ5DyGe8wdCdEi6wyk5MvlNQdqdVg5bqV0AiotIBcd5Pemabun2WaB11h/6SSb6wKY4Fnz+H155zaEww4no9BTG9llqQV7H8AS77dN1bxhcpE/MGFoB9JFU0D+BwXAnth4z1u";

    /**
     *商户签约时，支付包提供的公钥(RSA)*/
    public static final String ALIPAY_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx7jJT+PSEM6ZiimTW0SGUfg4cJU04H/mQqkL2mk7KaHXFQqMh4US6xYkDlaEXzOOfxevuBqWOaB4/8TleO1CHZHXWHu9Xc+iYtJPNJGrxoGLM+6Cg9IafJTygRoaqdH0SoVMpxFdOpUftNdXHO+G0ZpS/7c1zpn8G64zN5J17IFrLcUlsEnSgOrJxsS2Q50b44er0KQlj76pehB2sTveHS2vdhqXzrv+oq99XtUKEY1a3nwDjXneI7YYKLHD9KU53pti/ibLDkOEjO4+DRowd+wfSwkmWGVL3X320mvCfrg/aMN71B/cyyhW0mQ4cxqh2UcnpxLm0v/+uC7dSCyAJwIDAQAB";

    public static final String IP="http://8039d08.r5.cpolar.top";
    private static AlipayClient client;
    static {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(APP_ID);
        alipayConfig.setPrivateKey(PRIVATE_KEY);
        alipayConfig.setFormat("JSON");
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setAlipayPublicKey(ALIPAY_PUBLIC_KEY);
        alipayConfig.setSignType("RSA2");
        //构造client
        try {
            client = new DefaultAlipayClient(alipayConfig);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建支付
     * @param no 订单号
     * @param title 标题
     * @param money 订单金额 单位元*/
    public static String createPay(String no,String title,Double money){
        //1.创建请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //设置回调接口地址 公网可访问
        request.setNotifyUrl(IP+"/api/pay/alipaucb");
        //设置支付成功的回调页面 公网可访问
        request.setReturnUrl(IP+"/paysuccess.html");

        //2.设置请求参数
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //订单号
        model.setOutTradeNo(no);
        //订单标题
        model.setSubject(title);
        //订单金额
//        model.setTotalAmount(money+"");
        model.setTotalAmount("0.01");
        //商品码 固定
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        request.setBizModel(model);
        //3.获取响应,返回支付页面信息
        try {
            AlipayTradePagePayResponse response=client.pageExecute(request);
            if(response.isSuccess()){
                return response.getBody();
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * 查询支付状态
     * @param no 订单号
     * */
    public static String queryStatus(String no){
        //1.创建请求
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();


        //2.设置参数
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(no);
        request.setBizModel(model);

        //3.获取响应 返回结果
        try {
            AlipayTradeQueryResponse response=client.execute(request);
            if(response.isSuccess()){
                return response.getTradeStatus();
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * 发起退款
     * @param no 订单号
     * @param money 退款金额*/
    public static boolean refundPay(String no,Double money){
        //1.请求
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        //2.参数
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(no);
        model.setRefundAmount(money.toString());

        request.setBizModel(model);

        //3.响应
        try {
            AlipayTradeRefundResponse response=client.execute(request);
            if(response.isSuccess()){
                return response.getFundChange().toUpperCase().equals("Y");
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return false;
    }
    /**
     * 查询退款
     * @param no 订单号*/
    public static String queryRefund(String no){
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();

        AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
        model.setOutRequestNo(no);
        model.setOutTradeNo(no);
        request.setBizModel(model);


        try {
            AlipayTradeFastpayRefundQueryResponse response=client.execute(request);
            if(response.isSuccess()){
                return response.getRefundStatus();
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * 关闭支付
     * @param no 订单号*/
    public static String closePay(String no){
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
        model.setOutTradeNo(no);
        request.setBizModel(model);
        try {
            AlipayTradeCloseResponse response=client.execute(request);
            if(response.isSuccess()){
                return response.getMsg();
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * 查询对账单
     * @param date 账单日期
     * 日账单格式为yyyy-MM-dd*/
    public static String queryBillUrl(String date){

        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
        model.setBillType("trade");
        model.setBillDate(date);
        request.setBizModel(model);

        try {
            AlipayDataDataserviceBillDownloadurlQueryResponse response = client.execute(request);
            if(response.isSuccess()){
                return response.getBillDownloadUrl();
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

}
